package com.mauth.web.controller;

import com.mauth.common.dto.Result;
import com.mauth.common.dto.auth.ClientParameter;
import com.mauth.common.dto.auth.Token;
import com.mauth.common.entity.auth.UserRole;
import com.mauth.web.service.AuthService;
import com.mauth.web.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/oauth2")
@ResponseBody
public class AuthController {
    @Resource
    private AuthService authService;
    @Resource
    private UserService userService;
    @Value("${system.auth-server-url}")
    private String authUrl;

    @PostMapping("/authorize")
    public Token authorize(ClientParameter parameter,
                           @RequestHeader(value = "Authorization", required = false) String authorization) {
        if (authService.validAuth(parameter.getCode(), authorization)) {
            return authService.generateToken(parameter, authorization);
        }
        return null;
    }

    @GetMapping("/authorize")
    public void authorize_get(ClientParameter parameter,
                              HttpSession session, HttpServletResponse response) throws IOException {
        String uri = authUrl + "/login";
        if (authService.isLogin(parameter, session)) {
            String code = authService.generateCode(session);
            uri = parameter.getRedirect_uri() + "?code=" + code + "&state=" + parameter.getState();
        }
        String redirectUrl = response.encodeRedirectURL(uri);
        response.sendRedirect(redirectUrl);
    }

    @PostMapping("/token")
    public Token token(ClientParameter parameter,
                       @RequestHeader(value = "Authorization", required = false) String authorization) {
        return authorize(parameter, authorization);
    }

    @GetMapping("/test")
    public Result<String> test() {
        String code = RandomStringUtils.randomAlphanumeric(64);
        return Result.success().withData(code);
    }

    @GetMapping("/auth")
    public Result<UserRole> auth() {
        UserRole userRole = userService.getUserAuth(111);
        return Result.success().withData(userRole);
    }
}
